package com.yao.club.service.impl;

import com.yao.club.entity.UserEntity;
import com.yao.club.entity.dto.*;
import com.yao.club.entity.request.AddCarRequestEntity;
import com.yao.club.entity.request.UpdateCartItemRequest;
import com.yao.club.entity.request.DeleteCartItemRequest;
import com.yao.club.entity.result.ResponseEntity;
import com.yao.club.entity.vo.Category;
import com.yao.club.entity.vo.ShoppingCartResponseVO;
import com.yao.club.mapper.UserMapper;
import com.yao.club.reposittory.GoodsMainRepository;
import com.yao.club.reposittory.GoodsShoppingCarItemRepository;
import com.yao.club.reposittory.GoodsSkuRepository;
import com.yao.club.service.GoodsShoppingCarService;
import com.yao.club.utils.ResponseUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.Instant;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Service
public class GoodsShoppingCarServiceImpl implements GoodsShoppingCarService {

    @Autowired
    private GoodsShoppingCarItemRepository shoppingCarItemRepository;
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private GoodsMainRepository goodsMainRepository;

    @Autowired
    private GoodsSkuRepository goodsSkuRepository;
    @Override
    @Transactional
    public ResponseEntity<Boolean> addToCart(AddCarRequestEntity requestEntity, String username){
        try {
            UserEntity user = userMapper.select(username);
            if (user == null) {
                return ResponseUtils.failed("用户不存在");
            }
            GoodsMain goodsMain = goodsMainRepository.findById(requestEntity.getGoodsId()).get();
            if (goodsMain == null) {
                return ResponseUtils.failed("商品不存在");
            }
            if (goodsMain.getState().equals("vehicle")){
                return ResponseUtils.failed("是整车，不能添加购物车，请立即购买");
            }
            // 检查购物车中是否已存在该商品
            GoodsShoppingCarItem existingItem = shoppingCarItemRepository
                .findByGoodsIdAndGoodsSkuIdAndUserId(requestEntity.getGoodsId(), requestEntity.getGoodsSkuId(),user.getMember_id());

            if (existingItem != null) {
                // 如果已存在，更新数量
                existingItem.setNumber(existingItem.getNumber() + requestEntity.getNumber());
                shoppingCarItemRepository.save(existingItem);
            } else {
                // 如果不存在，保存新记录
                GoodsShoppingCarItem newItem = new GoodsShoppingCarItem();
                newItem.setUserId(user.getMember_id()); // 设置当前用户ID
                newItem.setGoodsId(requestEntity.getGoodsId());
                newItem.setGoodsName(requestEntity.getGoodsName());
                newItem.setGoodsSkuId(requestEntity.getGoodsSkuId());
                newItem.setGoodsSkuCode(requestEntity.getGoodsSkuCode());
                newItem.setGoodsSkuName(requestEntity.getGoodsSkuName());
                newItem.setNumber(requestEntity.getNumber());
                newItem.setCreateTime(Instant.now());

                newItem.setCategoryId(goodsMain.getCategoryId());
                newItem.setCategoryName(goodsMain.getCategoryName());
                newItem.setStocks(goodsMain.getStocks());
                newItem.setOnState(goodsMain.getState());
                newItem.setOnStateDesc(goodsMain.getState().equals("up") ? "上架":"下架");

                goodsSkuRepository.findById(requestEntity.getGoodsSkuId()).ifPresent(goodsSku -> {
                    newItem.setMainImageUrl(goodsSku.getSkuImgUrl());
                    newItem.setPrice(goodsSku.getPurchasePrice());
                    BigDecimal bigDecimal = new BigDecimal(requestEntity.getNumber());
                    newItem.setTotalPrice(newItem.getPrice().multiply(bigDecimal));
                });
                shoppingCarItemRepository.save(newItem);
            }
            return ResponseUtils.success(true);
        } catch (Exception e) {
            return ResponseUtils.failed("添加到购物车失败：" + e.getMessage());
        }
    }

    @Override
    public ResponseEntity<Integer> getShoppingCartCount(String username) {
        UserEntity user = userMapper.select(username);
        if (user == null) {
            return ResponseUtils.failed("用户不存在");
        }
        List<GoodsShoppingCarItem> items = shoppingCarItemRepository.findByUserId(user.member_id);
        int count = items.size(); // 计算购物车中的商品数量
        return ResponseUtils.success(count); // 假设你有一个成功的响应方法
    }

    @Override
    public ResponseEntity<ShoppingCartResponseVO> getShoppingCart(String username) {
        UserEntity user = userMapper.select(username);
        if (user == null) {
            return ResponseUtils.failed("用户不存在");
        }
        // 查询购物车中的商品
        List<GoodsShoppingCarItem> items = shoppingCarItemRepository.findByUserId(user.getMember_id());

        // 获取品牌和分类列表
        Set<Category> categories = new HashSet<>();
        for (GoodsShoppingCarItem item : items) {
            // 查询商品的分类信息
            GoodsMain goodsMain = goodsMainRepository.findById(item.getGoodsId()).orElse(null);
            if (goodsMain != null) {
                // 假设 MallGroup 是品牌的实体类
                Category category = new Category();
                category.setCategoryName(goodsMain.getCategoryName()); // 假设 GoodsMain 有品牌字段
                category.setCategoryId(goodsMain.getCategoryId());
                categories.add(category);
            }
        }

        ShoppingCartResponseVO response = new ShoppingCartResponseVO();
        response.setItems(items);
        response.setBrands(new ArrayList<>(categories)); // 转换为列表
        return ResponseUtils.success(response);
    }

    @Override
    @Transactional
    public ResponseEntity<Boolean> updateCartItem(UpdateCartItemRequest request, String username) {
        UserEntity user = userMapper.select(username);
        if (user == null) {
            return ResponseUtils.failed("用户不存在");
        }

        // 查找购物车中的商品
        GoodsShoppingCarItem existingItem = shoppingCarItemRepository.findById(Long.valueOf(request.getCarId())).orElse(null);
        
        if (existingItem == null || !existingItem.getUserId().equals(user.getMember_id())) {
            return ResponseUtils.failed("购物车中没有该商品或用户不匹配");
        }

        // 更新数量
        int newQuantity = request.getNumber();
        if (newQuantity < 0) {
            return ResponseUtils.failed("数量不能为负");
        }

        existingItem.setNumber(newQuantity);
        shoppingCarItemRepository.save(existingItem);
        return ResponseUtils.success(true);
    }

    @Override
    @Transactional
    public ResponseEntity<Boolean> deleteCartItem(DeleteCartItemRequest request, String username) {
        UserEntity user = userMapper.select(username);
        if (user == null) {
            return ResponseUtils.failed("用户不存在");
        }

        // 查找购物车中的商品
        GoodsShoppingCarItem existingItem = shoppingCarItemRepository.findById(Long.valueOf(request.getCarId())).orElse(null);
        
        if (existingItem == null || !existingItem.getUserId().equals(user.getMember_id())) {
            return ResponseUtils.failed("购物车中没有该商品或用户不匹配");
        }

        // 删除购物车项
        shoppingCarItemRepository.delete(existingItem);
        return ResponseUtils.success(true);
    }
} 